#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def sec2time(seg):
	hor = str (int(seg/60/60))
	min = str (int(seg/60)-int(hor)*60)
	seg = str (int(seg-int(seg/60)*60))	
	if len(min)  == 1:
		min = "0" + min
	if len(seg)  == 1:
		seg = "0" + seg
	return hor + ":" + min + ":" + seg

def time2sec(time):
	hor = time.split(':')[0]
	min = time.split(':')[1]
	seg = time.split(':')[2]
	return int(hor)*3600 + int(min)*60 + int(seg)

class TGeneral:
	def __init__(self, raw):
		self.__rawData = raw
		self.__titleNum = 0
		self.__seekable = 0
		self.__volumeId = ''
		self.__titulos = {}
		self.__mkvDesp = 0

	def getVolumeId(self):
		return self.__volumeId

	def getListTit(self):
		tmp = []
		for i in self.__titulos.keys():
			tmp += ['Titulo #' + str(i) + ' long: ' + sec2time(self.__titulos[i]['long']) + ' hr']
		return tmp

	def load(self):
		from re import search
		self.__seekable	= search 	("ID_SEEKABLE=(\d+)"	  	,	self.__rawData).groups()[0]
		try:
			self.__titleNum = int(search("ID_DVD_TITLES=(\d+)"	,	self.__rawData).groups()[0])
			self.__volumeId = search    ("ID_DVD_VOLUME_ID=(\w+)" 	,   self.__rawData).groups()[0]
			for i in range(1,self.__titleNum+1):
				chap 	= 	int(search	("ID_DVD_TITLE_"+str(i)+"_CHAPTERS=(\d+)"	,   self.__rawData).groups()[0])
				angles 	= 	int(search  ("ID_DVD_TITLE_"+str(i)+"_ANGLES=(\d+)"  	,   self.__rawData).groups()[0])
				long 	= 	int(search  ("ID_DVD_TITLE_"+str(i)+"_LENGTH=(\d+)"  	,   self.__rawData).groups()[0])
				self.__titulos [i] = {'chapters':chap, 'angles':angles, 'long':long} 
		except AttributeError, e:
			print 'Excepcion en General', e

		try:
			 self.__mkvDesp = int(search ('Track ID (\d+)', self.__rawData).groups()[0])
		except AttributeError, e:
			print 'Track ID (\d+)',e
		
	def str(self):
		return 'Info general',self.__titleNum, self.__seekable, self.__volumeId, [(i,self.__titulos [i]) for i in range(1,self.__titleNum+1)]
	

class TVideo:
	def __init__(self, raw):
		self.__rawData = raw
		self.__title = 0
		self.__angulos = 0
		self.__duracion = 0		
		self.__chapters = ''
		self.__numChapters = 0
		self.__format = 0
		self.__ancho = 0
		self.__alto = 0
		self.__aspect = 0
		self.__fps = 0
		self.__bitrate = 0
		self.__demuxer = ''
		self.__crop = ''

	def getDuracion(self):
		return self.__duracion
	def getListChapters(self):
		res = {}
		if self.__chapters:
			chaps = self.__chapters.split(',')
			for i in range(len(chaps)):
				if int(self.__numChapters) == i+1:
					chapSiguiente = self.__duracion
				else:
					chapSiguiente = time2sec(chaps[i+1]) 
				chapActual = time2sec(chaps[i])
				durac = int(chapSiguiente) - int(chapActual)
				res	[i+1] = {'durac':sec2time(durac), 'inicio':self.__chapters.split(',')[i]}
		return res

	def getCrop(self, data = ""):
		import re
		if not self.__crop:
			crops = []
			for i in data.split("\n"):
				try:
					crops.append(re.search("(\d+:\d+:\d+:\d+)\)", i).groups()[0])
				except AttributeError:
					pass
			maxCount = 0
			cropCmd = ""
			for i in crops:
				if crops.count(i) > maxCount:
					maxCount = crops.count(i)
					cropCmd = i
			self.__crop = cropCmd
		print self.__crop
		return self.__crop
	
	def str(self):
		return "info video", self.__angulos ,self.__duracion, self.__chapters, self.__bitrate,self.__aspect, self.__fps, self.__ancho, self.__alto, self.__format, self.__demuxer, self.__numChapters	

	
	def load(self):
		from re import search
		try:
			self.__title  		= search 		("ID_DVD_CURRENT_TITLE=(\d+)"	, 	self.__rawData).groups()[0]
		except AttributeError, e:
			self.__title = 0
			print e,"ID_DVD_CURRENT_TITLE"
		try:
			self.__angulos  	= search 		("ID_DVD_TITLE_"+str(self.__title)+"_ANGLES=(\d+)"	, 	self.__rawData).groups()[0]
		except AttributeError, e:
			self.__angulos = ""
			print e,'ID_DVD_TITLE_X_ANGLES'
		try:
			self.__chapters 	= search 		("CHAPTERS: (.*),",	self.__rawData).groups()[0] 
		except AttributeError, e:
			self.__chapters = ""
			print e, "CHAPTERS"
		
		self.__numChapters 	= search("ID_CHAPTERS=(\d+)"			,	self.__rawData).groups()[0] 
		self.__format	= search 	("ID_VIDEO_FORMAT=(\w+)"		,	self.__rawData).groups()[0]
		self.__ancho	= search 	("ID_VIDEO_WIDTH=(\d+)"			,	self.__rawData).groups()[0]
		self.__alto		= search 	("ID_VIDEO_HEIGHT=(\d+)"		,	self.__rawData).groups()[0]
		self.__aspect 	= search 	("ID_VIDEO_ASPECT=([1,2]\.\d+)"	,	self.__rawData).groups()[0]
		self.__fps 		= search 	("ID_VIDEO_FPS=(\d+\.\d+)"		,	self.__rawData).groups()[0]
		self.__bitrate 	= search 	("ID_VIDEO_BITRATE=(\d+)"		,	self.__rawData).groups()[0]
		self.__duracion	= int(search("ID_LENGTH=(\d+)"				, 	self.__rawData).groups()[0])
		self.__demuxer	= search 	("ID_DEMUXER=(\w+)"				,	self.__rawData).groups()[0]

class TAudio:
	def __init__(self, raw):
		self.__rawData = raw 
		self.__audios = {}

	def str(self):
		return [self.__audios [i] for i in self.__audios.keys()]

	def getListAudios(self):
		return self.__audios

	def getAudio(self, id):
		return self.__audios[id]

	def load(self):
		from re import search
		# for DVD
		try:
			for i in self.__rawData.split('\n'):
				if 'aid' in i:
					tmp = search(': (\d+) .*?: (\w+) \((.*?)\) .*?: (\w+) aid: (\d+).',i).groups()
					self.__audios[int(tmp[0])] = {'id':tmp[0], 'formato':tmp[1], 'ch':tmp[2],'idioma':tmp[3] ,'aid':tmp[4]} 
		except AttributeError, e:
			print e,i

		# for files without language
		try:
			for i in self.__rawData.split('\n'):
				if 'Stream' in i and 'Audio' in i:
					# Stream #0.1: Audio: mp3, 48000 Hz, stereo, s16, 32 kb/s
					tmp = search ('Stream #\d+\.(\d+): Audio:.*?(\w+),.*?(\d+).*?,.*?(\w+)',i).groups()
					self.__audios[int(tmp[0])] = {'id':tmp[0], 'formato':tmp[1], 'ch':tmp[3],'idioma':'und' ,'aid':tmp[0]} 
		except AttributeError, e:
			print e,i
		
		# for files with language
		try:
			for i in self.__rawData.split('\n'):
				if 'Stream' in i and 'Audio' in i:
					# Stream #0.1(eng): Audio: ac3, 48000 Hz, 5.1, s16
					tmp = search ('Stream #\d+\.(\d+)\((\w+)\): Audio:.*?(\w+),.*?(\d+).*?,.*?(.*?),',i).groups()
					self.__audios[int(tmp[0])] = {'id':tmp[0],'idioma':tmp[1], 'formato':tmp[2], 'ch':tmp[4],'aid':tmp[0]} 
		except AttributeError, e:
			print e,i


class TSubtitulos:
	def __init__(self, raw):
		self.__rawData = raw 
		self.__subtitulos = {}

	def str(self):
		return [self.__subtitulos [i] for i in self.__subtitulos.keys()]

	def getSubtitle(self, id):
		return self.__subtitulos[id]

	def getListSubtitles(self):
		return self.__subtitulos

	def load(self):
		from re import search
		# for DVD
		try:
			for i in self.__rawData.split('\n'):
				if 'sid' in i:
					tmp = search(': (\d+).*?: (\w+)',i).groups()
					self.__subtitulos[int(tmp[0])] = {'id':tmp[0], 'codec':'vobsub', 'sid': tmp[0], 'idioma':tmp[1] }
		except AttributeError, e:
			print e,i
		# for File
		try:
			for i in self.__rawData.split('\n'):
				if 'sid' in i:
					tmp = search('ID (\d+):.*?\((.*?)\), -sid (\d+), -slang (\w+)',i).groups()
					self.__subtitulos[int(tmp[0])] = {'id':tmp[0], 'codec':tmp[1], 'sid': tmp[2], 'idioma':tmp[3] }
		except AttributeError, e:
			print e,i

class TContenedor:
	def __init__(self, raw):
		self.__rawData = raw


from lector import TLector
class TDatos:
	def __init__(self, origen = '"/dev/dvd"'):
		self.__origen = origen
		self.__lector = TLector()
		self.__datos = {}

	def getOrigen(self):
		return self.__origen
	def getGeneral(self):
		return self.__datos['general']
	def getVideo(self, title):
		return self.__datos[title]['video']
	def getAudios(self, title):
		return self.__datos[title]['audio']
	def getSubtitles(self, title):
		return self.__datos[title]['subtitulos']
	def getCrop(self, title):
		if self.__datos[title]['video'].getCrop():
			return self.__datos[title]['video'].getCrop()
		else:
			return self.__datos[title]['video'].getCrop(self.__lector.getCropData(title, self.__datos[title]['video'].getDuracion()))
	def load(self, title = 0):
		self.__lector.setOrigen(self.__origen)
		self.__lector.addProgram('mplayer', '-v -identify -frames 1 -vo null -ao null', '-dvd-device ' + self.__origen + ' dvd://'+str(title),'-vo null -ao null -vf cropdetect -idx -nosound -frames 25 -speed 100')
		self.__lector.addProgram('ffmpeg', '-i', '','')
		self.__lector.addProgram('mkvmerge', '-i', '','')
		self.__lector.addProgram('file', '', '','')

		print title, self.__datos.keys()
		if title not in self.__datos.keys():
			self.__datos[title] = {}
			# get raw data
			self.__datos[title]['raw'] = self.__lector.getRawData(title)
			self.__datos['lector'] = self.__lector
			print self.__datos[title]['raw']
			# general data
			g = TGeneral(self.__datos[title]['raw'])
			g.load()
			self.__datos['general'] = g
			print g.str()
			# video Data
			v = TVideo(self.__datos[title]['raw'])
			v.load()
			self.__datos[title]['video'] = v
			print v.str()
			# audio Data
			a = TAudio(self.__datos[title]['raw'])
			a.load()
			self.__datos[title]['audio'] = a
			print a.str()
			# subtitle data
			s = TSubtitulos(self.__datos[title]['raw'])
			s.load()
			self.__datos[title]['subtitulos'] = s
			print s.str()

from sys import argv
if __name__ == "__main__":
	d = TDatos(argv[1])
	d.load(1)
	
		

